
package com.trial.area.user.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.trial.area.address.entity.DeliveryAddressVO;
import com.trial.area.address.service.DeliveryAddressService;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionUserInfo;
import com.trial.area.user.entity.UserInfoVO;
import com.trial.area.user.service.UserInfoService;
import com.trial.area.weixin.common.WeixinUtils;

/**
 * 用户信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class UserInfoController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;
    

    
    @Autowired
    DeliveryAddressService deliveryAddressService;

    private Logger logger = LoggerFactory.getLogger(UserInfoController.class);
    
    private static final String ACCOUNT_CENTER_PAGE = "/html5/account_center";
    
    @RequestMapping(value = "/check/account")
    public ModelAndView accountCenter() {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userInfoVO", seUser.getUserInfo());
        DeliveryAddressVO deliveryAddressVO = deliveryAddressService.findByUserId(seUser.getUserId());
        if (deliveryAddressVO != null) {
            resultMap.put("deliveryAddressId", deliveryAddressVO.getDeliveryAddressId());
        }
        return new ModelAndView(ACCOUNT_CENTER_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/loadNickName")
    public void loadNickName() {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        try {
            String realUrl = fullPath;
            
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            ApiConfig config = WeixinUtils.getApiConfig();
            // 第一次请求微信，获取code
            if (StringUtils.isBlank(code) && StringUtils.isBlank(state)) {
                String redirectUrl = SnsAccessTokenApi.getAuthorizeURL(config.getAppId(), URLEncoder.encode(realUrl, "UTF-8"), false);
                response.sendRedirect(redirectUrl);
                return;
                // 微信返回code，根据code获取openID
            } else if (StringUtils.isNotBlank(code)) {
                SnsAccessToken token = SnsAccessTokenApi.getSnsAccessToken(config.getAppId(), config.getAppSecret(), code);
                if (seUser == null) {
                    seUser = new SessionUserInfo();
                }
                // 根据openid获取注册过的用户信息
                UserInfoVO user = userInfoService.findById(null, token.getOpenid(), null);
                
                if (user != null) {
                    ApiConfigKit.setThreadLocalApiConfig(WeixinUtils.getApiConfig());
                    ApiResult weChartUser = UserApi.getUserInfo(token.getOpenid());
                    String nickName = URLEncoder.encode(weChartUser.getStr("nickname"), "UTF-8");

                    Integer subscribe = weChartUser.getInt("subscribe");

                    user.setNickName(nickName);
                    String headimgurl = weChartUser.getStr("headimgurl");
                    if (StringUtils.isBlank(headimgurl)) {
                        headimgurl = getPath() + "/images/touxiang.gif";
                    }
                    user.setHeadImage(headimgurl);

                    userInfoService.update(user);
                    
                    String userId = user.getUserId();
                    // 刷新session
                    seUser.setUserId(userId);
                    seUser.setUserName(user.getNickName());
                    
                    seUser.setSubscribe(subscribe);
                    
                    seUser.setUserInfo(user);
                    session.setAttribute("sessionUserInfo", seUser);
                }
            }
            
        } catch (Exception e) {
            logger.error("获取用户头像出错！", e);
        }
        try {
            response.sendRedirect(getPath() + "/check/account");
        } catch (Exception e) {
            logger.error("获取用户头像跳转到账户页出错！", e);
        }
    }

    @RequestMapping(value = "/uncheck/user/autoLogin")
    public void autoLogin() {
        String[] myRedirects = request.getParameterValues("myRedirect");
        String myRedirect = getPath() + "/index";
        if (myRedirects != null && myRedirects.length > 0) {
            myRedirect = myRedirects[0];
        }
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
            String invitationCode = (String) session.getAttribute("invitationCode");
            String userFrom = (String) session.getAttribute("userFrom");
            if (seUser == null) {
                String realUrl = fullPath;
                
                String code = request.getParameter("code");
                String state = request.getParameter("state");
                ApiConfig config = WeixinUtils.getApiConfig();
                // 第一次请求微信，获取code
                if (StringUtils.isBlank(code) && StringUtils.isBlank(state)) {
                    String redirectUrl = SnsAccessTokenApi.getAuthorizeURL(config.getAppId(), URLEncoder.encode(realUrl, "UTF-8"), true);
                    response.sendRedirect(redirectUrl);
                    return;
                    // 微信返回code，根据code获取openID
                } else if (StringUtils.isNotBlank(code)) {
                    SnsAccessToken token = SnsAccessTokenApi.getSnsAccessToken(config.getAppId(), config.getAppSecret(), code);

                    ApiConfigKit.setThreadLocalApiConfig(WeixinUtils.getApiConfig());
                    ApiResult weChartUser = UserApi.getUserInfo(token.getOpenid());
                    Integer subscribe = weChartUser.getInt("subscribe");
                    if (seUser == null) {
                        seUser = new SessionUserInfo();
                    }
                    if(StringUtils.isBlank(token.getOpenid())){
                    	response.sendRedirect(getPath() + "/index");
                    	return ;
                    }
                    // 根据openid获取注册过的用户信息
                    UserInfoVO user = userInfoService.findById(null, token.getOpenid(), null);
                    
                    if (user != null) {
                        String userId = user.getUserId();
                        // 刷新session
                        seUser.setUserId(userId);
                        seUser.setUserName(user.getNickName());
                        seUser.setSubscribe(subscribe);

                        seUser.setUserInfo(user);
                        
                        session.setAttribute("sessionUserInfo", seUser);
                        result.put("msg", "自动登录成功");
                        result.put("result", true);
                    } else {
                        user = new UserInfoVO();
                        String userId = UUID.randomUUID().toString();
                        user.setUserId(userId);
                        user.setDataStatus(0);
                        if (StringUtils.isNotBlank(invitationCode)) {
                            // 根据invitationCode获取注册过的用户信息
                            UserInfoVO investUser = userInfoService.findById(null, null, invitationCode);
                            if (investUser != null) {
                                user.setInvitationUser(investUser.getUserId());
                            }
                        }
                        
                        user.setOpenId(token.getOpenid());
                        user.setUserFrom(userFrom);
                        userInfoService.insert(user);
                        
                        // 刷新session
                        seUser.setUserId(userId);
                        seUser.setUserName(user.getNickName());
                        seUser.setSubscribe(subscribe);
                        
                        seUser.setUserInfo(user);
                        
                        session.setAttribute("sessionUserInfo", seUser);
                        result.put("msg", "获取用户微信openId成功，并自动注册");
                        result.put("result", true);
                    }
                    
                }
            }
            response.sendRedirect(myRedirect);
        } catch (Exception e) {
            logger.error("自动登录出错！", e);
            result.put("msg", "自动登录出错！");
            result.put("result", false);
        }

    }
}
